package src

import (
	"context"
	"fmt"
	"os"

	zd "gitee.com/haifengat/zorm-dm"
	"github.com/sirupsen/logrus"
)

var ctxDao context.Context // 数据库
var schameName = "CAS"

func initDB() {
	dmDSN := os.Getenv("dm")
	if dmDSN == "" {
		logrus.Fatal("postgres 未配置")
	}
	var err error
	if ctxDao, err = zd.InitDaoDM(dmDSN, schameName); err != nil {
		logrus.Fatal("打开数据库失败", err)
	}
	if err = zd.CreateSchema(ctxDao); err != nil {
		logrus.Fatal("创建数据库失败", err)
	}

	if err = zd.CreateTable[Policy](ctxDao); err != nil {
		logrus.Fatal("创建数据表 Policy", err)
	}
	if err = zd.CreateTable[Permission](ctxDao); err != nil {
		logrus.Fatal("创建数据表 Permission", err)
	}
	// 创建策略视图,拼接权限与角色(inner join 避免关联到失效的权限)
	if _, err = zd.ExecuteSql(ctxDao, fmt.Sprintf(`CREATE OR REPLACE  VIEW %s.CasbinPolicy AS 
SELECT po.PType, po.ROLE V0 , pe.APP V1, pe.URL V2, pe.ACTION V3
FROM %s.POLICY po
INNER JOIN %s.PERMISSION pe ON (po.PERMISSIONID = pe.UUID )
WHERE po.PTYPE = 'p'
UNION 
SELECT PType, ROLE , PERMISSIONID , '' URL ,'' ACTION
FROM %s.POLICY p 
WHERE p.PTYPE = 'g'`, schameName, schameName, schameName, schameName)); err != nil {
		logrus.Fatal("创建视图 CasbinPolicy", err)
	}
	logrus.Info("达梦: ", dmDSN)
}
